package com.plume.toolbox.plus;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.Person;
import androidx.fragment.app.DialogFragment;
import com.google.gson.Gson;
import com.hnphqs.nemoapi.URLContent;
import java.io.IOException;
import java.util.HashMap;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends DialogFragment{
    
    public void 不是咋的你还想破解登录啊(){}
    public void 你破解了也没用啊必须要token才能用(){}
    
    private View view;
    private OkHttpClient client = new OkHttpClient();
    private Handler mHandler = new Handler(Looper.getMainLooper());
    
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Inflate the layout for the dialog
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.activity_login, null);
        
        
        Button btnCancel = view.findViewById(R.id.cancel_btn);
        Button btnLogin = view.findViewById(R.id.login_btn);
        
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss(); // Close the dialog
            }
        });
        
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            showToast("登录中...");
                    
            String identity=((EditText)view.findViewById(R.id.identityEidtText)).getText().toString();
            String password=((EditText)view.findViewById(R.id.passwordEditText)).getText().toString();
            // 构建JSON数据字符串
            String json = 
            "{\"scene\":\"login\",\"pid\":\"T5qx9_w0\",\"identity\":\""+identity+"\",\"password\":\""+password+"\",\"timestamp\":"+Long.toString(System.currentTimeMillis())+"}";
            System.out.println(json);
            // 创建RequestBody
            RequestBody requestBody = RequestBody.create(
                    MediaType.parse("application/json"), json);


            Request request = new Request.Builder()
                    .url(URLContent.apiCaptcha())
                    .post(requestBody)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    showToast("登录失败! Faied to Post") ;             
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseData = response.body().string();
                    System.out.println(responseData);
                    HashMap data=new Gson().fromJson(responseData,HashMap.class);
                    
                     // 构建JSON数据字符串
                   // String json = 
                    //"{\"scene\":\"login\",\"pid\":\"T5qx9_w0\",\"identity\":\"yourPhoneNumber\",\"password\":\"yourPassword\",\"timestamp\":"+Long.toString(System.currentTimeMillis())+"}";
                    System.out.println(json);
                    // 创建RequestBody
                    RequestBody requestBody = RequestBody.create(
                    MediaType.parse("application/json"), json);
                                
                   // String ticket=(String)data.get("ticket");
                    String ticket=getTicketSafe(data);
                                
                    Request request = new Request.Builder()
                        .url(URLContent.apiLogin())
                        .header("X-Captcha-Ticket",ticket)   
                        .post(requestBody)
                        .build();          
                    client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        showToast("登录失败! Faied to Post") ; 
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();
                        System.out.println(responseData);
                        HashMap data=new Gson().fromJson(responseData,HashMap.class);                   
                        if (data.containsKey("error_message")){
                            UserInfoSaver.saveLoginStatus(getActivity(),false); 
                            UserInfoSaver.saveResponse(getActivity(),null);                  
                            showToast((String)data.get("error_message"));                    
                        }else{                   
                        UserInfoSaver.saveResponse(getActivity(),responseData);
                        UserInfoSaver.saveLoginStatus(getActivity(),true); 
                        showToast("登录成功!") ; 
                        dismiss();
                         }                                                             
                }
            });
                }
            });
                  // Close the dialog
            }
        });
        
        // Create the AlertDialog with the custom view
        return new AlertDialog.Builder(requireContext())
                .setView(view)
                .create();
    }
    public void showToast(final String message) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
            }
        });
    }
    public static String getTicketSafe( HashMap<String, Object> data){
               if (data == null) {
            return ""; // 或者返回默认值
        }
        // 检查ticket键是否存在
        if (!data.containsKey("ticket")) {
            return ""; // 或者返回默认值
        }
        try {
            return (String) data.get("ticket");
        } catch (ClassCastException e) {
            // 如果data.get("ticket")不是String类型
            return ""; // 或者返回默认值
        }
    }
}
